package com.maikang.exammall.api;

import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.maikang.exammall.entity.Order;
import com.maikang.exammall.entity.UserContext;
import com.maikang.exammall.entity.dto.FindAllRequest;
import com.maikang.exammall.entity.dto.ResponseDTO;
import com.maikang.exammall.entity.dto.order.*;
import com.maikang.exammall.service.OrderService;
import com.maikang.exammall.util.IPUtil;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

//import com.maikang.exammall.entity.dto.order.OrderDetailDTO;

@RestController
@RequiredArgsConstructor
@Log4j2
@RequestMapping("/api/orders")
public class OrderController {

    final private OrderService service;

    @ApiOperation("轮询支付状态")
    @GetMapping("/{outTradeNo}/pay-status")
    public ResponseDTO<Integer> pollPayStatus(@PathVariable("outTradeNo") String outTradeNo) {
        return ResponseDTO.ok(service.pollPayStatus(outTradeNo));
    }

    @PutMapping("/{outTradeNo}/second-pay")
    public ResponseDTO<WxPayMpOrderResult> launchSecondPay(@PathVariable("outTradeNo") String outTradeNo) {
        return ResponseDTO.ok(service.launchSecondPay(outTradeNo));
    }

    @PostMapping
    public ResponseDTO<CreateOrderOutputDTO> createOrder(@Valid @RequestBody CreateOrderInputDTO orderInput, HttpServletRequest request) {
        orderInput.setIp(IPUtil.getIpAddr(request));
        CreateOrderOutputDTO outputDTO = service.createOrder(orderInput);
        return ResponseDTO.ok(outputDTO);
    }

    @ApiOperation("根据status/name查询订单列表")
    @PostMapping(value = "/search")
    public ResponseDTO<Iterable<OrderDetailDTO>> findAll(@RequestBody FindAllRequest<SearchOrderInputDTO> findAllRequest) {
        Iterable<OrderDetailDTO> ret = service.findAll(findAllRequest.getConditions(), findAllRequest.getPageable().getPageable());
        return ResponseDTO.ok(ret);
    }

    @ApiOperation("根据status查询订单数量， 待支付：0， 待体检：2， 待评价： 6， 退款：3")
    @GetMapping(value = "/count")
    public ResponseDTO<Integer> countByStatus(@RequestParam(name = "status") Integer status ) {
        Integer count = service.countByStatus(status);
        return ResponseDTO.ok(count);
    }

    @DeleteMapping("/{id}")
    public ResponseDTO deleteById(@PathVariable("id") Long id) {
        log.info("going to delete record with primary key {}", id);
        Order order = Order.builder().userId(UserContext.getUserId()).id(id).invisibleToUser(true).build();
        service.save(order);
        return ResponseDTO.ok();
    }

    @GetMapping("/{id}")
    @Transactional(readOnly = true)
    public ResponseDTO<OrderDetailDTO> findByIdOrNull(@PathVariable("id") Long id) {
        OrderDetailDTO orderDetail = service.findByIdAndUserId(id, UserContext.getUserId());
        return ResponseDTO.ok(orderDetail);
    }

    @PutMapping("/refund/{id}")
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<Order> applyForRefund(@PathVariable("id") Long id, @Valid @RequestBody RefundOrderInputDTO input) {
        Order updated = service.applyOrderRefund(id, input);
        return ResponseDTO.ok(updated);
    }


    @ApiOperation("未付款状态下取消/关闭订单, 请求体传cancel_reason_id， remark")
    @PutMapping("/cancel/{id}")
    public ResponseDTO<Order> cancelOrder(@PathVariable("id") Long id, @Valid @RequestBody Order input) {
        Order updated = service.cancelOrder(id, input);
        return ResponseDTO.ok(updated);
    }

}
